import json
import random
from datetime import datetime, timedelta

from flask import request, current_app, g
from flask_restful import Resource

from model.news import Channel
from model.user import User, UserProfile
from toutiao import redis_cli, db, app

from utils.jwt import generate_jwt, verify_jwt
from utils.login_required import login_required

from utils.send_message import send_messages


class UserResouce(Resource):
    def get(self,mobile):
        code = str(random.randint(1000,9999))
        # mobile = send_messages(mobile,code)
        print(code)
        redis_cli.setex(mobile,120,code)
        return {'message':'ok,','data':{'mobile':mobile}}




class AuthorizationResource(Resource):
    """
    认证
    """
    def _generate_tokens(self, user_id, with_refresh_token=True):
        """
        生成token 和refresh_token
        :param user_id: 用户id
        :return: token, refresh_token
        """
         # 颁发JWT
        now = datetime.utcnow()
        expiry = now + timedelta(hours=2)
        token = generate_jwt({'user_id': user_id, 'refresh': False}, expiry)
        refresh_token = None
        if with_refresh_token:
            refresh_expiry = now + timedelta(days=current_app.config['JWT_REFRESH_DAYS'])
            refresh_token = generate_jwt({'user_id': user_id, 'refresh': True}, refresh_expiry)
        return token, refresh_token

    def post(self):
        """
        登录创建token
        """
        data = json.loads(request.data.decode())
        mobile = data.get('mobile')
        code = data.get('code')
        # 从redis中获取验证码
        key = 'app:code:{}'.format(mobile)
        try:
            real_code = redis_cli.get(mobile)
        except ConnectionError as e:
            current_app.logger.error(e)
            real_code = redis_cli.get(mobile)
        # try:
        #     redis_cli.delete(mobile)
        # except ConnectionError as e:
        #     current_app.logger.error(e)
        if not real_code or real_code.decode() != code:
            return {'message': 'Invalid code.'}, 400
        # 查询或保存用户
        user = User.query.filter_by(mobile=mobile).first()
        if user is None:
            # 用户不存在，注册用户
            user_id = User.query.all()[-1].id + 1
            user = User(id=user_id, mobile=mobile, name=mobile, last_login=datetime.now())
            db.session.add(user)
            profile = UserProfile(id=user.id)
            db.session.add(profile)
            db.session.commit()
        else:
            if user.status == User.STATUS.DISABLE:
                return {'message': 'Invalid user.'}, 403

        token, refresh_token = self._generate_tokens(user.id)

        # return {'token': token, 'refresh_token': refresh_token}, 201
        return  {"message": "ok","data": {"token": token,"refresh_token":refresh_token}}
    # 补充put方式 更新token接口
    def put(self):
        """
        刷新token
        """
        id = g.user_id
        if id and g.is_refresh_token:
            token, refresh_token = self._generate_tokens(id, with_refresh_token=False)
            return {'token': token}, 201
        else:
            return {'message': 'Wrong refresh token.'}, 403







class Userinfo(Resource):
    @login_required
    def get(self):
        obj =User.query.get(g.user_id)
        response = {
            'message':'ok',
            'data':{
                "id": obj.id,
                "name": obj.name,
                "photo": obj.profile_photo,
                "intro":obj.introduction,
                "art_count": obj.article_count,
                "follow_count": obj.following_count,
                "fans_count": obj.fans_count
            }
        }
        return response


class Channels(Resource):
    @login_required
    def get(self):
        data =Channel.query.get(user_id=g.user_id)
        list = []
        for i in data:
            list.append({
                'id':i.id,
                'name':i.name
            })
        return {"message": "OK","data":list}